#include "lwip/udp.h"
#include "config.h"
#include "app_api.h"

/* ============================== Private Functions =================================== */
static void udp_echo_server_cb(void *arg, struct udp_pcb *upcb, struct pbuf *p, \
                                ip_addr_t *addr, u16_t port)
{
    uint32_t i;

    printf("recv msg from %d:%d:%d:%d port:%d:\r\n",
           *((uint8_t *)&addr->addr), *((uint8_t *)&addr->addr + 1),
           *((uint8_t *)&addr->addr + 2), *((uint8_t *)&addr->addr + 3), port);

    if (p != NULL) {
        struct pbuf *ptmp = p;

        while (ptmp != NULL) {
            for (i = 0; i < p->len; i++) {
                printf("%c", *((char *)p->payload + i));
            }

            ptmp = p->next;
        }

        printf("\n");
    }

    pbuf_free(p);
}

/* ============================== Public Functions =================================== */
err_t udp_echo_server_init(void)
{
    err_t ret;
    struct udp_pcb *pcb;
    /* create udp pcb */
    pcb = udp_new();

    if(pcb) {
        ret = udp_bind(pcb, IP_ADDR_ANY, UDP_ECHO_SERVER_PORT);
        if(ret == ERR_OK) {
            udp_recv(pcb, udp_echo_server_cb, NULL);
        }
        else {
            udp_remove(pcb);
            printf("udp bind failed\n");
            return ERR_IF;
        }
    }

    return ERR_OK;
}